<template>
	<view class="container">
		<view class="title">注册账号</view>
		<uni-forms ref="formRef" :rules="rules" :modelValue="formData">
			<view class="section">
				<view class="form">
					<view class="form-item">
						<view class="group" @click="isShowPopup = true">
							<view class="number">{{ areaCode }}</view>
							<view class="arrow">
								<image class="img" src="@/static/images/shape.png"></image>
							</view>
						</view>
						<view class="cell">
							<uni-forms-item required name="phone">
								<uni-easyinput
									v-model="formData.phone" placeholder="请输入手机号码"
									:placeholderStyle="inputPlaceholderStyle" :input-border="false" trim :clearable="false"
								/>
							</uni-forms-item>
						</view>
					</view>
					<view class="form-item">
						<view class="cell">
							<uni-forms-item required name="code">
								<uni-easyinput
									v-model="formData.code" placeholder="请输入验证码"
									:placeholderStyle="inputPlaceholderStyle" :input-border="false" trim :clearable="false"
								/>
							</uni-forms-item>
						</view>
						<text class="tips" @click="sendVerificationCode">{{ prompts }}</text>
					</view>
					<view class="form-item">
						<view class="cell">
							<uni-forms-item required name="password">
								<uni-easyinput
									type="password" v-model="formData.password" placeholder="请输入新密码"
									:placeholderStyle="inputPlaceholderStyle" :input-border="false" trim :clearable="false"
								/>
							</uni-forms-item>
						</view>
					</view>
					<view class="form-item">
						<view class="cell">
							<uni-forms-item required name="pwdAgain">
								<uni-easyinput
									type="password" v-model="formData.pwdAgain" placeholder="请重新输入密码"
									:placeholderStyle="inputPlaceholderStyle" :input-border="false" trim :clearable="false"
								/>
							</uni-forms-item>
						</view>
					</view>
				</view>
				<view class="term" @click="toggleCheckStatus">
					<view class="checkbox" :class="{active: checked}"></view>
                    <text>我已阅读并同意</text>
					<text class="agreement">《用户协议》</text>
				</view>
				<view class="actions">
					<z-button @click="submit">注册</z-button>
				</view>
			</view>
		</uni-forms>
		<z-popup class="popup" v-model="isShowPopup" has-head title="地区选择" round="32rpx" @confirm="handleConfirm" @cancel="handleCancel">
			<picker-view indicator-style="height: 50px" :value="currentIndex" @change="handlePickerChange" class="picker-view">
				<picker-view-column>
					<view class="entry" v-for="(nation, index) in nations" :key="index">{{ nation }}</view>
				</picker-view-column>
			</picker-view>
		</z-popup>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { validatePhoneNumber, validateCode, validatePassword } from '@/utils/validate'
import { inputPlaceholderStyle } from '@/utils/common'
import { register } from '@/api/index'

const formRef = ref()
const formData = reactive({
    phone: '',
    code: '',
    password: '',
	pwdAgain: ''
})
const rules = ref({
	phone: {
        rules: [
			{ required: true, errorMessage: '请输入手机号码' },
            { validateFunction: validatePhoneNumber }
		]
    },
	code: {
		rules: [
			{ required: true, errorMessage: '请输入验证码' },
            { validateFunction: validateCode }
		]
	},
	password: {
		rules: [
			{ required: true, errorMessage: '请输入密码' },
            { validateFunction: validatePassword }
		]
	},
	pwdAgain: {
		rules: [
			{ required: true, errorMessage: '请再次输入密码' }
		]
	}
})
const checked = ref(false)
const isShowPopup = ref(false)
const nations = ref(['+86 中国', '+60 马来西亚', '+07 俄罗斯', '+01 美国'])
const currentIndex = ref([0])
const areaCode = ref('+86')
const prompts = ref('获取验证码')
let countdown = 60
let countingDown = false

const sendVerificationCode = async () => {
    if (formRef.value) {
        const result = await formRef.value.validateField('phone').catch(() => false)
        if(result && !countingDown) {
            countingDown = true
            let timer = setInterval(() => {
                countdown--
                if (countdown === 0) {
                    clearInterval(timer)
                    countingDown = false
                    countdown = 60
                    prompts.value = '重新获取验证码'
                } else {
                    prompts.value = `${countdown.toString().padStart(2, '0')}s`
                }
            }, 1000)
        }
    }
}

const submit = async () => {
	if(!checked.value) {
        return uni.showToast({ title: '请阅读并勾选协议', icon: 'none' })
    }
	if (formRef.value) {
        const result = await formRef.value.validate().catch(() => false)
        if(result) {
			const { password, pwdAgain } = result
            if(password === pwdAgain ) {
				const { pwdAgain, phone: username, ...params } = formData
				const { code } = await register({ username, ...params })
				if(code==200) {
					const { confirm } = await uni.showModal({
						title: '提示',
						content: '注册成功！',
						showCancel: false,
						confirmText: '确认'
					}).catch(() => false)
					if(confirm) {
						uni.redirectTo({ url: '/pages/login/login' })
					}
				} else {
					uni.showToast({ title: msg || '系统异常!', icon: 'none' })
				}
            } else {
                uni.showToast({ title: '您两次输入的密码不一致', icon: 'none' })
            }
		}
	}
}

const handleConfirm = () => {
	isShowPopup.value = false
	areaCode.value = nations.value[currentIndex.value]
}

const handleCancel = () => {
	isShowPopup.value = false
}

const handlePickerChange = ({ detail: { value } }) => {
	currentIndex.value = value
}

const toggleCheckStatus = () => {
	checked.value = !checked.value
}
</script>

<style lang="scss">
.container {
	padding: 76rpx 32rpx 0 32rpx;
	height: 100vh;
	background-color: #fff;
	font-family: PingFang SC, PingFang SC;
	.title {
		font-size: 44rpx;
		color: #222;
		font-weight: bold;
	}
	::v-deep .uni-forms {
        .uni-forms-item {
            margin-bottom: 0;
            &__label {
                display: none !important;
            }
            &__content {
                .uni-input-placeholder {
                    color: #BFBFBF;
                }
                .uni-forms-item__error {
					top: calc(100% + 8rpx);
                    text {
                        white-space: nowrap;
                    }
                }
				.uni-easyinput__content-input {
					padding: 0 !important;
					font-size: 32rpx;
				}
            }
        }
    }
	.section {
		margin-top: 72rpx;
		.form {
			margin-bottom: 32rpx;
			.form-item {
				display: flex;
				align-items: center;
				padding: 0 40rpx;
				height: 88rpx;
				border-radius: 44rpx;
				background-color: #F7F8FA;
				&:not(:last-child) {
					margin-bottom: 32rpx;
				}
				.group {
					display: flex;
					padding-right: 16rpx;
					border-right: 3rpx solid #E3E3E3;
					margin-right: 20rpx;
					.number {
						font-size: 32rpx;
						color: #000;
						margin-right: 4rpx;
					}
					.arrow {
						width: 24rpx;
						height: 12rpx;
						.img {
							height: 100%;
						}
					}
				}
				.cell {
					flex: 1;
				}
				.tips {
					padding-left: 20rpx;
					color: #0080FF;
				}
			}
		}
		.term {
			display: inline-block;
			font-size: 28rpx;
			color: #999;
			.checkbox {
				transform: translateY(-2rpx);
                display: inline-block;
                margin-right: .5em;
                vertical-align: middle;
                width: 28rpx;
                height: 28rpx;
                border: 2rpx solid #ccc;
                border-radius: 50%;
                box-sizing: border-box;
                &.active {
                    position: relative;
                    background-color: #0080FF;
                    border: none;
                    &::before {
                        position: absolute;
                        top: 25%;
                        left: 25%;
                        content: '';
                        display: block;
                        height: 6rpx;
                        width: 14rpx;
                        border-left: 2rpx solid #fff;
                        border-bottom: 2rpx solid #fff;
                        transform: rotate(-45deg);
                    }
                }
            }
			.agreement {
				color: #0080FF;
			}
		}
		.actions {
			margin-top: 32rpx;
		}
	}
	.popup {
		.picker-view {
			width: 100%;
			height: 400rpx;
			margin-top: 20rpx;
			.entry {
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
}
</style>
